package com.xc.freeapp.account.controller;

import java.util.HashMap;
import java.util.Map;

import javax.validation.Valid;


import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.xc.freeapp.bean.AuthInfo;
import com.xc.freeapp.common.CheckUtils;
import com.xc.freeapp.common.ResponseBean;
import com.xc.freeapp.entity.Hospital;
import com.xc.freeapp.entity.UserLiving;
import com.xc.freeapp.entity.Users;
import com.xc.freeapp.exception.BaseException;
import com.xc.freeapp.redis.VerificationCodeDao;
import com.xc.freeapp.request.bean.Register;
import com.xc.freeapp.request.bean.ResetBean;
import com.xc.freeapp.service.HospitalService;
import com.xc.freeapp.service.RegisteredService;
import com.xc.freeapp.service.UsersService;
import com.xc.freeapp.service.impl.UserLivingServiceImpl;
import com.xc.freeapp.util.AuthUtil;
import com.xc.freeapp.util.Constant;
import com.xc.freeapp.util.DateUtils;
import com.xc.freeapp.util.TokenAnnotation;
import com.xc.freeapp.util.UploadUtil;

import com.xc.freeapp.util.JwtUtil;

@Controller
@RequestMapping("/accountCenter")
@Api(value = "/accountCenter", description = "账户中心")
public class AccountController extends AbstractController {
	private Logger log = Logger.getLogger(this.getClass());
	@Autowired
	RegisteredService registeredServiceImpl;
	@Autowired
	private UsersService usersServiceImpl;
	@Autowired
	UserLivingServiceImpl userLivingServiceImpl;
	@Autowired
	private HospitalService hospitalService;
	@Autowired
	VerificationCodeDao verificationCodeDaoImpl;

	/**
	 * 获取验证码接口
	 * 
	 * @param request
	 * @return
	 */
	@TokenAnnotation(required = false)
	@RequestMapping(value = "/verificationCode", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "获取验证码接口")
	public ResponseBean getVerificationCode(
			@RequestParam(value = "telephone") String telephone)
			throws BaseException {

		Map<String, String> map = new HashMap<String, String>();
		try {
			CheckUtils.matchPattern(Constant.VER_NOTNULL, telephone,
					"^1\\d{10}$");
			map.put("telephone", telephone);
			registeredServiceImpl.getVerificationCode(map);// 验证码入redis和发送
			return ResponseBean.getSuccess();
		} catch (BaseException e) {
			log.error("申请验证码接口出错" + e.getMessage());
			throw e;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("申请验证码接口出错");
			throw new BaseException(Constant.COMMON_ERROR);
		}
	}

	/**
	 * 用户注册接口
	 * 
	 * @param request
	 * @return
	 */
	@TokenAnnotation(required = false)
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "用户注册接口")
	public Map registerUser(@RequestBody @Valid Register register)
			throws BaseException {

		Map<String, Object> responseMap = new HashMap<String, Object>();
		AuthInfo authInfo = AuthUtil.getAuthInfo(getRequest());
		Map<String, String> map = new HashMap<String, String>();
		map.put("appId", authInfo.getAppId());
		map.put("registerType", authInfo.getPlatform());
		map.put("telephone", register.getTelephone());
		map.put("loginPwd", register.getLoginPwd());
		map.put("verificationCode", register.getVerificationCode());
		map.put("registrationId", register.getRegistrationId());
		try {
			registeredServiceImpl.register(map);
		} catch (BaseException e) {
			throw e;
		} catch (Exception e) {
			e.printStackTrace();
			// TODO Auto-generated catch block
			throw new BaseException(Constant.COMMON_ERROR);
		}
		Users user = usersServiceImpl.login(register.getTelephone(),
				register.getLoginPwd(), authInfo.getAppId());

		user.setLoginpwd("");
		if (user != null) {
			responseMap.put("user", user);
			responseMap.put("token",
					JwtUtil.sign(authInfo.getAppId(), user.getUserid()));
			log.info("token=" + "token_" + user.getUserid());
			verificationCodeDaoImpl.put("token_" + user.getUserid(),
					responseMap.get("token").toString(), 60000000);
		}
		return responseMap;

	}

	/**
	 * 非签署页调用）用户登录
	 * 
	 * @param register
	 * @return
	 * @throws BaseException
	 */
	@TokenAnnotation(required = false)
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "用户登录")
	public Map mobileAction_login(@RequestBody @Valid Register register)
			throws BaseException {
		Map<String, Object> responseMap = new HashMap<String, Object>();
		AuthInfo authInfo = AuthUtil.getAuthInfo(getRequest());
		String loginName = "";
		try {
			log.info("（非签署页调用）用户" + loginName + "登录");
			Users user = usersServiceImpl.login(register.getTelephone(),
					register.getLoginPwd(), authInfo.getAppId());
			if (user != null) {
				Users userupdate = new Users();
				user.setIcon(UploadUtil.urlConversion(user.getIcon()));
				responseMap.put("user", user);
				responseMap.put("token",
						JwtUtil.sign(authInfo.getAppId(), user.getUserid()));
				verificationCodeDaoImpl.put("token_" + user.getUserid(),
						responseMap.get("token").toString(), 60000000);
				if (register.getRegistrationId() != null
						&& !"".equals(register.getRegistrationId())) {
					userupdate.setUserid(user.getUserid());
					userupdate.setRegistrationid(register.getRegistrationId());
					usersServiceImpl.updateuserinfo(userupdate);
				}
				user.setLoginpwd("");
				return responseMap;
			} else {
				throw new BaseException(Constant.ERRORCODE_105);
			}
		} catch (BaseException e) {
			log.error(loginName + ":登陆出错" + "账号不存在或者密码错误");
			throw e;
		} catch (Exception e) {
			log.error(loginName + ":登陆出错" + e.getMessage());
			throw new BaseException(Constant.COMMON_ERROR);
		}
	}

	/**
	 * 保存极光推送id
	 * 
	 * @param register
	 * @return
	 * @throws BaseException
	 */
	@TokenAnnotation(required = false)
	@RequestMapping(value = "/saveregistrationid", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "保存极光推送id")
	public Map mobileAction_login(@RequestParam String registrationid)
			throws BaseException {
		Map<String, Object> responseMap = new HashMap<String, Object>();
		AuthInfo authInfo = AuthUtil.getAuthInfo(getRequest());
		String loginName = "";
		try {

			log.info("（非签署页调用）用户" + loginName + "登录");
			Users user = usersServiceImpl.getUserInfo(authInfo.getUserId());
			if (user != null) {
				Users userupdate = new Users();
				user.setIcon(UploadUtil.urlConversion(user.getIcon()));
				responseMap.put("user", user);

				if (registrationid != null && !"".equals(registrationid)) {
					userupdate.setUserid(user.getUserid());
					userupdate.setRegistrationid(registrationid);
					usersServiceImpl.updateuserinfo(userupdate);
				}
				user.setLoginpwd("");
				return responseMap;
			} else {
				throw new BaseException(Constant.COMMON_ERROR);
			}
		} catch (BaseException e) {
			log.error(loginName + ":登陆出错" + "账号不存在或者密码错误");
			throw e;
		} catch (Exception e) {
			log.error(loginName + ":登陆出错" + e.getMessage());
			throw new BaseException(Constant.COMMON_ERROR);
		}
	}

	/**
	 * 重置密码接口
	 * 
	 * @param newloginpw
	 * @param verificationCode
	 * @return
	 * @throws BaseException
	 */
	@TokenAnnotation(required = false)
	@RequestMapping(value = "/resetLoginwd", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "重置密码接口")
	public ResponseBean resetLoginwd(@RequestBody @Valid ResetBean ResetBean)
			throws BaseException {
		AuthInfo authInfo = AuthUtil.getAuthInfo(getRequest());
		log.info("ResetBean=" + ResetBean);
		try {
			Map<String, String> map = new HashMap<String, String>();
			map.put("businessId", authInfo.getAppId());
			map.put("telephone", ResetBean.getTelephone());
			map.put("newloginpw", ResetBean.getNewloginpw());
			map.put("verificationCode", ResetBean.getVerificationCode());
			registeredServiceImpl.resetLoginwd(map);
			return ResponseBean.getSuccess();
		} catch (BaseException e) {
			log.error(authInfo.getUserId() + ":重置密码出错" + e.getMessage());
			throw e;
		} catch (Exception e) {
			log.error(authInfo.getUserId() + ":重置密码出错" + e.getMessage());
			throw new BaseException(Constant.COMMON_ERROR);
		}
	}

	@TokenAnnotation(required = false)
	@RequestMapping(value = "/openApp", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "统计日活")
	public ResponseBean openApp() throws BaseException {
		UserLiving userLiving = new UserLiving();
		AuthInfo authInfo = AuthUtil.getAuthInfo(getRequest());

		userLiving.setAppid(authInfo.getAppIntId());
		userLiving.setUserid(authInfo.getUserIntId());
		userLiving.setUserdate(DateUtils.getDate());
		userLiving.setCreatetime(DateUtils.getDate());
		if ("ios".equals(authInfo.getPlatform())) {
			userLiving.setDevicetype(2);
		}
		if ("android".equals(authInfo.getPlatform())) {
			userLiving.setDevicetype(1);
		}

		userLiving.setUpdatetime(DateUtils.getDate());
		userLivingServiceImpl.insert(userLiving);
		return ResponseBean.getSuccess();
	}

	@TokenAnnotation(required = false)
	@RequestMapping(value = "/qrcode", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "二维码")
	public Map<String, String> qrcode() throws BaseException {
		Map<String, String> map = new HashMap<String, String>();
		AuthInfo authInfo = AuthUtil.getAuthInfo(getRequest());
		Hospital hospital = hospitalService.selectByPrimaryKey(authInfo
				.getAppIntId());
		map.put("qrcode",
				UploadUtil.urlConversion("app_download_" + hospital.getAppid()
						+ ".jpg"));
		return map;
	}
}
